package UserInterface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;

import DataReading.LoadSystem;


public class initUI extends JFrame {
	
	public Timer timer = new Timer(initUI.currentSliderValue, new TimerListener());
	double timeToSend = 0;
	double timeToDisplay = 0;
	public Timer secondTimer = new Timer(100, new MyTimerListener());
	private JMenuBar menuBar; // menu bar
	private JMenu fileMenu; // file
	private JMenu aboutMenu; // about
	private JMenuItem exit; // exit
	private JMenuItem developers; // developers sub-menu
	private JMenuItem version; // version sub-menu
	private JPanel imagePanel; // top panel
	private JPanel textPanel; // middle panel
	private JPanel buttonPanel; // bottom panel
	private JLabel radarImage; // image of the radar, part of the imagePanel
	private JLabel userPrompt; // "Please enter filename to parse (extension included)" part of the textPanel
	private JTextField fileText; // Text field to enter filename, part of the textPanel
	private JButton okButton; // "OK" button, part of the textPanel
	private JButton tableButton; // "Table" button, part of the buttonPanel
	private JButton gridButton; // "Grid" button, part of the buttonPanel
	final int WINDOW_WIDTH = 800;
	final int WINDOW_HEIGHT = 800;
	boolean validFile = false; // boolean determining if the filename entered was valid
	private tableUI table; 
	private gridUI grid; 
	public static LoadSystem system;
	String inputFile;
	static String shipTypes[] = {"Human (swimmer)", "Speed Boat", "Fishing Boat", "Cargo Vessel", "Passenger Vessel"};
	static int currentSliderValue;
	public static String optionSelected; // guest or admin
	
	public initUI(String string){
		
		optionSelected = string;
		setTitle("Radar Simulator -- " + string); // sets window title (string determines administrator or guest)
		setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // sets window size
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close when red X is clicked
		buildImagePanel(); // builds the image panel (method defined lower)
		add(imagePanel, BorderLayout.NORTH); // add the imagePanel to the frame
		buildTextPanel(); // builds the panel (method defined lower)
		add(textPanel); // adds textPanel to the frame
		buildButtonPanel(); // build the buttonPanel (method defined below)
		add(buttonPanel, BorderLayout.SOUTH);
		buildMenuBar();
		setVisible(true); // makes the window visible
	}
	
	private void buildUIs(){
		table = new tableUI(this, system); // creates but does not make visible yet
		grid = new gridUI(this, table, system); // creates but does not make visible yet
		table.grid = grid;
	}
	
	public class TimerListener implements ActionListener{
		
		public void actionPerformed(ActionEvent e){		
			if (timeToSend >= system.getInfo().getTime()) {
				timeToSend = system.getInfo().getTime();
				//timer.stop();
			}
			
			system.updateVessalPositions(timeToSend);
			table.updateTable();
			grid.repaint();
	        //System.out.println(system.displayTable());
			timeToSend += timer.getDelay() / 1000.00;
	        
	        
		}
	}
	
	public class MyTimerListener implements ActionListener{
		
		public void actionPerformed(ActionEvent e){
			timeToDisplay += secondTimer.getDelay() / 1000.00;
			if (timeToDisplay >= system.getInfo().getTime()) {
				timeToDisplay = system.getInfo().getTime();
				//timer.stop();
			}
			BigDecimal roundedTime = new BigDecimal(timeToDisplay).setScale(1, RoundingMode.CEILING);
			grid.timerField.setText("Time Elapsed: " + roundedTime + "s");
			table.timerField.setText("Time Elapsed: " + roundedTime + "s");
		}
	}

	
	
	private void buildMenuBar(){ // menu bar method
		
		menuBar = new JMenuBar();
		buildFileMenu();
		buildAboutMenu();
		
		menuBar.add(fileMenu);
		menuBar.add(aboutMenu);
		menuBar.setBackground(Color.BLACK);
		setJMenuBar(menuBar);
		
	}
	private void buildFileMenu(){ // file menu
		
		exit = new JMenuItem("Exit");
		exit.setMnemonic(KeyEvent.VK_X); // sets mnemonic for exit option
		exit.addActionListener(new ExitListener()); // adds listener for exit option
		
		fileMenu = new JMenu("File");
		fileMenu.setMnemonic(KeyEvent.VK_F); // sets mnemonic for file option
		fileMenu.setForeground(Color.ORANGE);
		fileMenu.add(exit); // adds exit under file menu
	}
	
	private void buildAboutMenu(){ // about menu
		
		developers = new JMenuItem("Developers");
		developers.setMnemonic(KeyEvent.VK_D); // sets mnemonic for developers option
		developers.addActionListener(new AboutListener());
		version = new JMenuItem("Version");
		version.setMnemonic(KeyEvent.VK_V); // sets mnemonic for version option
		version.addActionListener(new AboutListener());
		
		aboutMenu = new JMenu("About");
		aboutMenu.setMnemonic(KeyEvent.VK_A); // sets mnemonic for developers option
		aboutMenu.setForeground(Color.ORANGE);
		aboutMenu.add(developers); // adds developers into about sub-menu
		aboutMenu.add(version); // adds version into about sub-menu
	}
	
	private class AboutListener implements ActionListener{ // listener called when sub-options of about are clicked
		
		public void actionPerformed(ActionEvent e){
			
			if(e.getSource() == developers){
					JOptionPane.showMessageDialog(null,  "Anne Rahman\n" + "Daniel Neagoe\n"+
												 "Enamul Quazi\n"+ "Eric Robitaille\n"+
												 "Harkanwal Singh Narula\n"+ "Noah Reboh", "Developers", 
												 JOptionPane.PLAIN_MESSAGE); // message box
			}
			else if(e.getSource() == version){
				JOptionPane.showMessageDialog(null, "Version 1.3", "Version", JOptionPane.PLAIN_MESSAGE); // message box
			}
		}
	}
	
	private class ExitListener implements ActionListener{ // listener called when exit is clicked
		
		public void actionPerformed(ActionEvent e){
			System.exit(0); // system exit
		}
	}
	private void buildImagePanel(){ // top panel method
		
		ImageIcon image = new ImageIcon("radar.jpg"); // fetches image
		radarImage = new JLabel(image); // adds image to the label
		imagePanel = new JPanel(); // creates panel
		imagePanel.add(radarImage); // adds image to the panel
	}
	
	private void buildTextPanel(){ // middle panel method
			
		userPrompt = new JLabel("Please enter the filename of the ship data (extension included): "); // creates label
		userPrompt.setForeground(Color.ORANGE); // sets text color to white
		userPrompt.setFont(new Font("Arial", Font.BOLD, 14)); // sets font size
		fileText = new JTextField(15); // creates text box of size 10
		fileText.addActionListener(new textListener()); // adds action listener to text field (to press enter)
		okButton = new JButton("OK"); // creates OK button
		okButton.addActionListener(new textListener()); // adds listener to the OK button
		textPanel = new JPanel(); //creates the panel
		textPanel.setBackground(Color.BLACK); // creates black background for the middle panel
		textPanel.add(userPrompt); // adds label
		textPanel.add(fileText); // adds text field
		textPanel.add(okButton); // adds button
	}
	
	private void buildButtonPanel(){ // bottom panel method
		
		tableButton = new JButton("Table"); // creates table button
		tableButton.setPreferredSize(new Dimension(300, 90)); // sets button size
		tableButton.setFont(new Font("Arial", Font.BOLD, 20)); // sets font size
		tableButton.addActionListener(new buttonListener()); // adds listener to table button
		gridButton = new JButton("Grid"); // creates grid button
		gridButton.setPreferredSize(new Dimension(300, 90)); // sets button size
		gridButton.setFont(new Font("ARIAL", Font.BOLD, 20)); // sets font size
		gridButton.addActionListener(new buttonListener()); // adds listener to grid button
		buttonPanel = new JPanel(); // creates the panel
		buttonPanel.setBackground(Color.BLACK); // sets color of button panel to black
		buttonPanel.add(tableButton); // add the table button
		buttonPanel.add(gridButton); // add the grid button
	}
	
	private class buttonListener implements ActionListener{ // private inner class for all buttons
		
		public void actionPerformed(ActionEvent e){
			
			if (e.getSource() == tableButton){ // checks which button was pressed
				
				if (!validFile){ // if valid filename was not previously entered
					JOptionPane.showMessageDialog(null, "Enter a valid filename first", "Warning", 
													JOptionPane.WARNING_MESSAGE); //message box
				}
				
				else{
					setVisible(false); // hide the initial UI
					table.setVisible(true); // makes the table visible
				}
			}
			
			else if (e.getSource() == gridButton){ // checks which button was pressed
				
				if (!validFile){ // if valid filename was not previously entered
					JOptionPane.showMessageDialog(null, "Enter a valid filename first", "Warning", 
													JOptionPane.WARNING_MESSAGE); //message box
				}
				
				else{
					setVisible(false); // hide the initial UI
					grid.setVisible(true); // makes the grid visible
				}			
			}
		}
	}
	
	private class textListener implements ActionListener{
		
		public void actionPerformed(ActionEvent e){
			
			inputFile = fileText.getText(); // gets the text input by the user
			
			try{ // attempt to open the file
				
				File fileToRead = new File(inputFile);
				Scanner input = new Scanner(fileToRead);
				validFile = true;
				system = new LoadSystem(inputFile); //pass inputFile to the load system class
				currentSliderValue = system.getInfo().getTimeStep() * 1000;
				timer.setDelay(currentSliderValue);
				timeToSend = system.getInfo().getStartTime();
				buildUIs();
				JOptionPane.showMessageDialog(null, "Valid filename. Buttons activated", "Success", // message box
												JOptionPane.INFORMATION_MESSAGE);
				input.close();
			}
			catch (FileNotFoundException error){ // catch statement if file isn't found
				
				validFile = false;
				JOptionPane.showMessageDialog(null, "File not found", "Error", JOptionPane.ERROR_MESSAGE); //message box
			}
		}
	}
}
